<template>
	<div class="profile">
		<div class="profile-title">{{$t('message.profileNow')}}</div>
		<p class="profile-tip">{{$t('message.profileNowDescribe')}}</p>
		<div class="profile-avatar">
			<img :src="userProfile"/>
		</div>
		<div class="profile-title">{{$t('message.profileEdit')}}</div>
		<p class="profile-tip">{{$t('message.profileEditDescribe')}}</p>
		<div class="profile-upload">
			<div class="profile-original">
				<img v-if="status === 'clip'" :src="uploadImage" ref="originalImage" draggable="false" :class="{ 'profile-original-width': isWidthLong, 'profile-original-height': !isWidthLong }"/>
				<div class="profile-clip" v-if="status === 'clip'" :style="clipStyle" @mousedown="moveClip">
					<div class="clip-bar bar-north" @mousedown.stop="resizeNorth"></div>
					<div class="clip-bar bar-west" @mousedown.stop="resizeWest"></div>
					<div class="clip-bar bar-east" @mousedown.stop="resizeEast"></div>
					<div class="clip-bar bar-south" @mousedown.stop="resizeSouth"></div>
					<div class="clip-point point-top-left" @mousedown.stop="resizeNorthWest"></div>
					<div class="clip-point point-top-center" @mousedown.stop="resizeNorth"></div>
					<div class="clip-point point-top-right" @mousedown.stop="resizeNorth"></div>
					<div class="clip-point point-center-left"@mousedown.stop="resizeWest"></div>
					<div class="clip-point point-center-right" @mousedown.stop="resizeEast"></div>
					<div class="clip-point point-bottom-left"@mousedown.stop="resizeWest"></div>
					<div class="clip-point point-bottom-center" @mousedown.stop="resizeSouth"></div>
					<div class="clip-point point-bottom-right" @mousedown.stop="resizeSouthEast"></div>
				</div>
				<!--loading-->
				<div class="profile-loading" v-if="status === 'loading'">
					{{ $t('message.uploadLoading') }}
				</div>
			</div>
			<div class="profile-new" v-show="status === 'clip' || status === 'loading'">
				<canvas width="120" height="120" ref="canvas"></canvas>
			</div>
		</div>
		<input type="file" v-show="false" ref="uploadImage" @change="onFileChange" />
		<button type="button" v-if="status === 'null'" class="profile-btn profile-image" @click="triggerUpload">{{$t('message.uploadImageBtn')}}</button>
		<div class="profile-btn-group" v-if="status === 'clip'">
			<button type="button" class="profile-btn profile-save" @click="save">{{$t('message.save')}}</button>
			<button type="button" class="profile-btn profile-cancel" @click="cancel">{{$t('message.cancel')}}</button>
		</div>
	</div>
</template>

<script>
import {setCookie} from '@/util/util'

export default {
  name: 'PersonalAccountProfile',
  data () {
    return {
      profile: null,
      uploadImage: '',
      isWidthLong: true,
      scale: 1,
      sx: 40,
      sy: 40,
      swidth: 160,
      imgNaturalWidth: 0,
      imgNaturalHeight: 0,
      status: 'null'
    }
  },
  computed: {
    userProfile () {
      if (this.profile) {
        return this.profile
      } else {
        return require('../../../assets/images/personal/account/profile_default.png')
      }
    },
    clipStyle () {
      return {
        width: this.swidth + 'px',
        height: this.swidth + 'px',
        left: this.sx + 'px',
        top: this.sy + 'px'
      }
    },
    imgCurrentWidth () {
      return this.imgNaturalWidth * this.scale
    },
    imgCurrentHeight () {
      return this.imgNaturalHeight * this.scale
    },
    imgTop () {
      return (240 - this.imgCurrentHeight) / 2
    },
    imgLeft () {
      return (240 - this.imgCurrentWidth) / 2
    },
    currentSx () {
      return (this.sx + 1 - this.imgLeft) / this.scale
    },
    currentSy () {
      return (this.sy + 1 - this.imgTop) / this.scale
    },
    currentSwidth () {
      return this.swidth / this.scale
    }
  },
  methods: {
    // 获得头像
    getProfile () {
      this.$ajax.getUserInfo().then(res => {
        if (res.code === 200) {
          this.profile = res.data.head_portrait
          setCookie('profile', res.data.head_portrait)
        }
      })
    },
    triggerUpload () {
      this.$refs.uploadImage.click()
    },
    onFileChange (e) {
      if (!e.target.files && !e.dataTransfer) {
        alert(this.$t('message.uploadTip2'))
        return
      }
      let files = e.target.files || e.dataTransfer.files
      if (files.length === 0) {
        return
      } else {
        this.createImage(files)
      }
    },
    createImage (files) {
      if (typeof FileReader === 'undefined') {
        alert(this.$t('message.uploadTip2'))
        return
      }
      let reader = new FileReader()
      reader.readAsDataURL(files[0])
      reader.onload = (e) => {
        this.uploadImage = e.target.result
        this.drawCanvas()
      }
    },
    draw () {
      if (this.swidth < 40) {
        this.swidth = 40
      }
      if (this.swidth > this.imgCurrentWidth) {
        this.swidth = this.imgCurrentWidth
      }
      if (this.swidth > this.imgCurrentHeight) {
        this.swidth = this.imgCurrentHeight
      }
      if (this.sx < this.imgLeft - 1) {
        this.sx = this.imgLeft - 1
      }
      if (this.sy < this.imgTop - 1) {
        this.sy = this.imgTop - 1
      }
      if (this.sy + this.swidth + 1 > this.imgTop + this.imgCurrentHeight) {
        this.sy = this.imgTop + this.imgCurrentHeight - this.swidth - 1
      }
      if (this.sx + this.swidth + 1 > this.imgLeft + this.imgCurrentWidth) {
        this.sx = this.imgLeft + this.imgCurrentWidth - this.swidth - 1
      }
      let c = this.$refs.canvas
      let ctx = c.getContext('2d')
      ctx.clearRect(0, 0, c.width, c.height)
      ctx.drawImage(this.$refs.originalImage, this.currentSx, this.currentSy, this.currentSwidth, this.currentSwidth, 0, 0, 120, 120)
    },
    drawCanvas () {
      this.status = 'clip'
      let image = new Image()
      image.onload = () => {
        this.sx = 40
        this.sy = 40
        this.swidth = 160
        this.imgNaturalWidth = image.naturalWidth
        this.imgNaturalHeight = image.naturalHeight
        if (image.naturalWidth > image.naturalHeight) {
          this.isWidthLong = true
          this.scale = 240 / image.naturalWidth
        } else {
          this.isWidthLong = false
          this.scale = 240 / image.naturalHeight
        }
        // 如果裁剪宽度大于图片的实际宽度
        if (image.naturalWidth * this.scale < this.swidth) {
          this.swidth = this.imgCurrentWidth
          this.sx = this.imgLeft - 1
          this.sy = this.imgLeft - 1
        }
        // 如果裁剪高度大于图片的实际高度
        if (image.naturalHeight * this.scale < this.swidth) {
          this.swidth = this.imgCurrentHeight
          this.sy = this.imgTop - 1
          this.sx = this.imgTop - 1
        }
        this.draw()
      }
      image.src = this.uploadImage
    },
    moveClip (e) {
      let _this = this
      let startX = e.clientX - this.sx
      let startY = e.clientY - this.sy
      document.onmousemove = function (e) {
        _this.sx = e.clientX - startX
        _this.sy = e.clientY - startY
        _this.draw()
      }
      this.removeEvent()
    },
    resizeNorthWest (e) {
      let _this = this
      let startX = e.pageX
      let x = this.sx
      let y = this.sy
      let width = this.swidth
      document.onmousemove = function (e) {
        if (_this.swidth > 40) {
          _this.sx = x + e.pageX - startX
          _this.sy = y + e.pageX - startX
        }
        _this.swidth = width - (e.pageX - startX)
        _this.draw()
      }
      this.removeEvent()
    },
    resizeNorth (e) {
      let _this = this
      let startY = e.pageY
      let y = this.sy
      let width = this.swidth
      document.onmousemove = function (e) {
        if (_this.swidth > 40) {
          _this.sy = y + e.pageY - startY
        }
        _this.swidth = width - (e.pageY - startY)
        _this.draw()
      }
      this.removeEvent()
    },
    resizeWest (e) {
      let _this = this
      let startX = e.pageX
      let x = this.sx
      let width = this.swidth
      document.onmousemove = function (e) {
        if (_this.swidth > 40) {
          _this.sx = x + e.pageX - startX
        }
        _this.swidth = width - (e.pageX - startX)
        _this.draw()
      }
      this.removeEvent()
    },
    resizeEast (e) {
      let _this = this
      let startX = e.pageX
      let width = this.swidth
      document.onmousemove = function (e) {
        _this.swidth = width + e.pageX - startX
        _this.draw()
      }
      this.removeEvent()
    },
    resizeSouthEast (e) {
      let _this = this
      let startX = e.pageX
      let startY = e.pageY
      let width = this.swidth
      document.onmousemove = function (e) {
        let valX = e.pageX - startX
        let valY = e.pageY - startY
        let val = valX > valY ? valX : valY
        _this.swidth = width + val
        _this.draw()
      }
      this.removeEvent()
    },
    resizeSouth (e) {
      let _this = this
      let startY = e.pageY
      let width = this.swidth
      document.onmousemove = function (e) {
        _this.swidth = width + (e.pageY - startY)
        _this.draw()
      }
      this.removeEvent()
    },
    removeEvent () {
      document.onmouseup = function (e) {
        document.onmousemove = null
        document.onmouseup = null
      }
    },
    save () {
      let data = this.$refs.canvas.toDataURL()
      this.status = 'loading'
      this.$ajax.updateProfile({
        img: data
      }).then((res) => {
        if (res.code === 200) {
          this.status = 'null'
          this.uploadImage = false
          this.getProfile()
        } else {
          console.log('上传失败')
        }
      })
    },
    cancel () {
      this.$refs.uploadImage.value = ''
      this.uploadImage = ''
      this.status = 'null'
    }
  },
  created () {
    this.getProfile()
  }
}
</script>

<style scoped>
.profile {
	padding-left: 18px;
}

.profile-title {
	height: 22px;
	line-height: 22px;
	font-size: 16px;
	font-weight: bold;
	margin-top: 60px;
	position: relative;
}

.profile-title:before {
	content: '';
	display: block;
	width: 4px;
	height: 16px;
	background-color: #ff600a;
	position: absolute;
	top: 4px;
	left: -18px;
}

.profile-tip {
	height: 20px;
	line-height: 20px;
	font-size: 14px;
	color: #a5a5a5;
	margin-top: 10px;
}

.profile-avatar {
	width: 60px;
	height: 60px;
	border-radius: 50%;
	margin-top: 24px;
	overflow: hidden;
}

.profile-avatar img {
	width: 100%;
	height: 100%;
}

.profile-upload {
	margin-top: 24px;
	overflow: hidden;
}

.profile-original {
	float: left;
	width: 240px;
	height: 240px;
	border: 1px solid #e6e6e6;
	background-color: #fafafa;
	text-align: center;
	line-height: 238px;
	position: relative;
}

.profile-original img {
	max-width: 240px;
	max-height: 240px;
	-webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}

.profile-original-width {
	width: 100%;
}

.profile-original-height {
	height: 100%;
}

.profile-clip {
	border: 1px dashed #979797;
	cursor: move;
	position: absolute;
	-webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}

.clip-bar {
}

.bar-north {
	width: 100%;
	height: 6px;
	position: absolute;
	top: -1px;
	left: 0;
	cursor: n-resize;
}

.bar-west {
	width: 6px;
	height: 100%;
	position: absolute;
	top: 0;
	left: -1px;
	cursor: w-resize;
}

.bar-east {
	width: 6px;
	height: 100%;
	position: absolute;
	top: 0;
	right: -1px;
	cursor: e-resize;
}

.bar-south {
	width: 100%;
	height: 6px;
	position: absolute;
	bottom: -1px;
	left: 0;
	cursor: s-resize;
}

.clip-point {
	width: 6px;
	height: 6px;
	background-color: #999;
	position: absolute;
}

.point-top-left {
	top: -1px;
	left: -1px;
	cursor: nw-resize;
}

.point-top-center {
	top: -1px;
	left: 50%;
	margin-left: -3px;
	cursor: n-resize;
}

.point-top-right {
	top: -1px;
	right: -1px;
	cursor: ne-resize;
}

.point-center-left {
	top: 50%;
	left: -1px;
	margin-top: -3px;
	cursor: w-resize;
}

.point-center-right {
	top: 50%;
	right: -1px;
	margin-top: -3px;
	cursor: e-resize;
}

.point-bottom-left {
	bottom: -1px;
	left: -1px;
	cursor: sw-resize;
}

.point-bottom-center {
	bottom: -1px;
	left: 50%;
	margin-left: -3px;
	cursor: s-resize;
}

.point-bottom-right {
	bottom: -1px;
	right: -1px;
	cursor: se-resize;
}

.profile-loading {
  line-height: 17px;
  font-size: 12px;
  color: #a5a5a5;
  margin-top: 100px;
  padding-top: 40px;
  background: url(../../../assets/images/upload_loading.gif) no-repeat center top;
}

.profile-new {
	float: left;
	width: 120px;
	height: 120px;
	margin-left: 60px;
}

.profile-new canvas {
	-webkit-user-select:none;
  -moz-user-select:none;
  -ms-user-select:none;
  user-select:none;
}

.profile-btn {
	width: 110px;
	height: 44px;
	font-size: 14px;
	cursor: pointer;
	-webkit-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
}

.profile-image {
	border: none;
	background-color: #ff600a;
	color: #fff;
	margin-top: 40px;
}

.profile-image:hover, .profile-save:hover {
	background-color: #ff3c00;
}

.profile-image:active, .profile-save:active {
	background-color: #e83700;
}

.profile-btn-group {
	font-size: 0;
	margin-top: 40px;
}

.profile-save {
	border: none;
	background-color: #ff600a;
	color: #fff;
}

.profile-cancel {
	border: 1px solid #ff600a;
	background-color: #fff;
	color: #ff600a;
	margin-left: 20px;
}

.profile-cancel:hover {
	background-color: #ff600a;
	color: #fff;
}

.profile-cancel:active {
	background-color: #e83700;
	color: #fff;
}
</style>